(function () {

    var app = {
        //version: '0.21'
        version: '1.34',
        debug: false
    };
    var lastBackKeyTime = -1452455;

    function onDeviceReadyAndDocumentReady() {

        var platform = device.platform;
        $(document.body).addClass(platform);

        //alert(platform);
        var deviceSb = false;
        if (platform == 'iOS') {
            deviceSb = true;
            app.isIos = true;
        }
        else if (platform == 'browser') {
            //deviceSb = true; //test
            app.isBrowser = true;
        }
        else if (platform == 'Android') {
            app.isAndroid = true;
        }
        if (deviceSb) {
            $(document.body).addClass('device-sb');
        }
        if (app.isIos) {
            $(document.body).addClass('ios');
        }
        if (!app.isBrowser) {
            // 网络连接检测
            app.checkConnection();
        }
        //$('#splashOverlay').hide();
        $('#init_cover').hide();
        if (navigator.splashscreen) {
            setTimeout(function () {
                navigator.splashscreen.hide();
            }, 1234);
        }

        //
        setTimeout(function () {
            kendo.init($('#_confirm_dlg'));
        }, 0);

        //
        !inBrowser &&
        cordova.plugins &&
        cordova.plugins.test1Plugin &&
        cordova.plugins.test1Plugin.listenSendFile(function (fileInfo) {
            onGotFile(fileInfo);
        });
    }

    function onGotFile(fileInfo) {
        //alert('GOT: ' + fileInfo.name + ', ' + fileInfo.content.substr(0, 60));
        backService.hrec.file.save(null, null, [fileInfo.name], [fileInfo.content],
            function (result) {
                var file = result.data;
                console.log('Got: ' + file.name);
                $(document).trigger('_hrecFileAdded');
                app.gotoPage('/hrec/file/show_pdf.html?id=' + file.id);
            });
    }

    app.confirm2 = function (title, content, emphasis, callback) {
        if (typeof(emphasis) === 'function') {
            callback = emphasis;
            emphasis = false;
        }
        var $dlg = $('#_confirm_dlg');
        $dlg.toggleClass('emphasis', !!emphasis);
        $dlg.find('.title').text(title);
        var $content = $dlg.find('.content');
        if (content) {
            $dlg.removeClass('no-content');
            $content.html(content.replace(/\n/g, '<br/>'));
        }
        else {
            $dlg.addClass('no-content');
            //$content.html('');
        }
        $dlg.off('click').on('click', 'a', function (e) {
            e.preventDefault();
            var $a = $(this);
            var index = $a.index();
            if (index === 1) {
                callback();
            }
            $dlg.hide();
        });
        $dlg.show();
    };

    app.showPopupMenu2 = function (items, selectedIndex, callback) {
        if (typeof(selectedIndex) === 'function') {
            callback = selectedIndex;
            selectedIndex = null;
        }

        var $popupMenu = $('#_popup_menu');
        var $menu = $popupMenu.find('.menu');
        var $ul = $menu.find('ul');
        kendo.destroy($ul);
        $ul.empty();
        for (var n = 0; n < items.length; n++) {
            var $li = $('<li><a href="#!" data-role="link">' + items[n] + '</a></li>');
            if (n === selectedIndex) {
                $li.addClass('checked');
            }
            $li.appendTo($ul);
        }
        kendo.init($ul);
        $popupMenu.show();
        $popupMenu.off('click').on('click', function (e) {
            e.preventDefault();
            $popupMenu.hide();
            if (!$.contains($menu[0], e.target)) {
                callback(-1);
            }
            else {
                var index = $(e.target).closest('li').index();
                callback(index);
            }
        });

    };

    function _makeAbsoluteUrl(base, relative) {
        var stack = base.split("/"),
            parts = relative.split("/");
        stack.pop(); // remove current file name (or empty string)
                     // (omit if "base" is the current folder without trailing slash)
        for (var i = 0; i < parts.length; i++) {
            if (parts[i] == ".")
                continue;
            if (parts[i] == "..")
                stack.pop();
            else
                stack.push(parts[i]);
        }
        return stack.join("/");
    }

    app.gotoPage = function (url, transition, callback) {
        if (typeof transition == 'function') {
            callback = transition;
            transition = undefined;
        }
        var url0 = url;
        var c0 = url.charAt(0);
        if (c0 == '/') {
            if (url.length > 1) {
                url = url.substr(1);
            }
            else {
                url = kendo.history.locations[0];
            }
        }
        else if (c0 == '#') {
            url = url.substr(1);
        }
        else {
            var currentUrl = kendo.history.current;
            //alert('@' + currentUrl);
            if (currentUrl == '/') {
                currentUrl = '';
            }
            url = _makeAbsoluteUrl(currentUrl, url);
        }
        app.gotoPageCallback = callback;
        //alert('-> ' + url + '(' + url0 + ')');
        kendoApp.navigate(url, transition);
    };

    //
    //var absUrlRe = /((src|href)=['"])\//g;
    var absUrlRe = /(src=['"])\//g;
    app.preprocessHtml = function (html) {
        html = html.replace(absUrlRe, "$1");
        return html;
    };


    //
    app._onDeviceReady = function () {
        //alert('device ready..');
        app.deviceReady = true;
        if (app.docReady) {
            onDeviceReadyAndDocumentReady();
        }

        // document.addEventListener("backbutton", app.onBackKeyDown, false);

    };

    app.checkConnection = function () {
        /*var networkState = navigator.network.connection.type;
        var states = {};
        states[Connection.UNKNOWN] = '未知的连接';
        states[Connection.ETHERNET] = '以太网连接';
        states[Connection.WIFI] = '无线网络连接';
        states[Connection.CELL_2G] = '2G连接';
        states[Connection.CELL_3G] = '3G连接';
        states[Connection.CELL_4G] = '4G连接';
        states[Connection.NONE] = '亲，网络断了，请检查网络连接';

        // app.showToast(states[networkState], 3000);
        return networkState;*/
    };


    //
    app.initialize = function () {
        document.addEventListener('deviceready', app._onDeviceReady, false);
        app.startTime = new Date();

        $.ajaxSetup({
            timeout: 14000
        });

        $(document).ready(app._onDocReady);
    };

    app._onDocReady = function () {
        app.docReady = true;
        if (app.deviceReady) {
            onDeviceReadyAndDocumentReady();
        }
        //
        var oriArea = $(window).width() * $(window).height();
        $(window).resize(function () {
            if ($(window).width() * $(window).height() < oriArea * 0.8) {
                $(document.body).addClass('keyboard');
            } else {
                $(document.body).removeClass('keyboard');
            }
        });
    };

    //
    app.onKendoAppInit = function () {

        //kendo.history.bind('back', function() {
        //    console.log('xxxx');
        //});

    };

    //
    //app.showLoadingCount = 0;
    //app.showLoading = function () {
    //    //kendoApp.showLoading();
    //    if(app.showLoadingCount == 0) {
    //        $('#ui_loader').show();
    //    }
    //    ++app.showLoadingCount;
    //    return app.showLoadingCount;
    //};
    //
    //app.hideLoading = function (cookie) {
    //    //if(cookie !== undefined && cookie != app.showLoadingCount) {
    //    //    return;
    //    //}
    //    if(app.showLoadingCount == 0) {
    //        return;
    //    }
    //    //kendoApp.hideLoading();
    //    --app.showLoadingCount;
    //    if(app.showLoadingCount == 0) {
    //        $('#ui_loader').hide();
    //    }
    //};

    var loadingCount = 0;
    var nextLoadingCookie = 1;
    var loadingCookies = {};
    var forceHideLoaderTimer;

    function forceHideLoader() {
        loadingCount = 0;
        loadingCookies = {};
        $('#ui_loader').hide();
    }

    app.showLoading = function () {
        if (loadingCount == 0) {
            kendoApp.showLoading();
        }
        ++loadingCount;
        var cookie = nextLoadingCookie++;
        loadingCookies[cookie] = true;
        clearTimeout(forceHideLoaderTimer);
        forceHideLoaderTimer = setTimeout(forceHideLoader, 1000 * 20);
        //console.log('@ show loading...(' + cookie + ')');
        return cookie;
    };

    app.hideLoading = function (cookie) {
        //console.log('@ hide loading...(' + cookie + ')');
        if (cookie !== undefined && !(cookie in loadingCookies)) {
            return;
        }
        if (loadingCount == 0) {
            return;
        }
        --loadingCount;
        if (loadingCount == 0) {
            clearTimeout(forceHideLoaderTimer);
            kendoApp.hideLoading();
            loadingCookies = {};
        }
    };

    //
    app.showToast = function (msg, timeout) {
        new Android_Toast({content: msg, duration: timeout || 2200});
    };


    //
    //app.openExternal = function (url) {
    //    //if (device.platform === 'Android') {
    //    if (navigator.app && navigator.app.loadUrl) {
    //        navigator.app.loadUrl(url, {openExternal: true});
    //    }
    //    else {
    //        window.open(url, '_system');
    //    }
    //};

    app.returnUrl = function (url, callback) {
        var url0 = url;
        var locations = kendo.history.locations;

        if (typeof(url) == 'number') {
            url = locations[locations.length - 1 + (url)];
            if (url == "") {
                app.gotoPage("/");
            }
            // console.log(url);
        } else if (url.charAt(0) == '/') {
            if (url.length > 1) {
                url = url.substr(1);
            }
            else {
                url = locations[0];
            }
        } else {
            var currentUrl = kendo.history.current;
            if (currentUrl == '/') {
                currentUrl = '';
            }
            url = _makeAbsoluteUrl(currentUrl, url);
        }

        var urlLength = url.length;
        var inHistory = false;
        for (var n = locations.length - 1; n >= 0; --n) {
            if (locations[n].substr(0, urlLength) == url) {
                inHistory = true;
                url = locations[n];
                break;
            }
            //++backCount;
        }
        //if(backCount == 0) {
        //if(url.)
        if (!inHistory) {
            url = url0;
        } else {
            if (url.charAt(0) != '/') {
                url = '/' + url;
            }
        }
        app.gotoPage(url, "slide:right", callback);
        //}
        //else {
        //    history.go(-backCount);
        //}
    };

    app.alert = function (msg, callback, title) {
        var _alert = window.navigator.notification &&
            window.navigator.notification.alert ||
            window.alert;
        _alert(msg, callback, title || '提示', '确定');
    };

    app.confirm = function (prompt, callback, title, buttonLabels) {
        if (!title) {
            title = '提示';
        }
        if (!buttonLabels) {
            buttonLabels = ["确定", "取消"];
        }
        navigator.notification.confirm(prompt, callback, title, buttonLabels);
    };

    //
    app.openExternal = function (url) {
        if (navigator.app && navigator.app.loadUrl) {
            navigator.app.loadUrl(url, {openExternal: true});
        }
        else {
            window.open(url, '_system');
        }
    };

    //
    app.setViewBackUrl = function (view, url) {
        if (typeof(view) == 'string') {
            url = view;
            view = null;
        }
        if (!view) {
            view = kendoApp.view();
        }
        var backButton = view.element.find('.km-back').data('kendoMobileBackButton');
        view.bind('show', function () {
            backButton.bind('click', function (e) {
                app.gotoPage(url);
                e.preventDefault();
            });
        });
        view.bind('hide', function () {
            backButton.unbind('click');
        });
    };

    // 设置app标题栏名称
    app.setViewTitle = function (title) {
        var view = kendoApp.view();
        view.options.title = title;
        var $viewTitle = view.element.find('.km-view-title');
        var $title = $viewTitle.find('span[data-role=view-title], .title');
        if ($title.length) {
            $title.text(title);
        }
        else {
            $viewTitle.text(title);
        }
    };

    app.setViewBackText = function (text) {
        var view = kendoApp.view();
        var $viewLeft = view.element.find('.km-leftitem');
        var $Text = $viewLeft.find('a[data-role="backbutton"], .back');
        if ($Text.length) {
            $Text.text(text);
        }
    }

    //
    app.disableViewOnBackServiceLoading = function (view) {
        if (!view) {
            view = kendoApp.view();
        }
        view.element.on('click', 'a', function () {
            if (backService.requests.length) {
                return false;
            }
        });
    };

    //
    app.disableButtons = function ($as) {
        $as.each(function () {
            $(this).data('kendoMobileButton').enable(false);
        });
    };

    //
    app.logout = function () {
        window.session = {};
        backService.localLoginInfo = null;
        localStorage.removeItem('loginInfo');
        app.gotoPage('/user/login.html');
    };

    app.toMain = function () {
        app.gotoPage("/");
    };

    app.waitFrameReady = function (frame, callback) {
        function _wait() {
            var frameWindow = frame.contentWindow;
            if (!frameWindow || !frameWindow.ready) {
                setTimeout(_wait, 50);
            }
            else {
                callback(frameWindow);
            }
        }

        _wait();
    };

    window.disableBackButtonCallback = function (e) {
        e.preventDefault();
    };

    app.disableBackKey = function (view) {
        view.bind('show', function () {
            document.addEventListener('backbutton', disableBackButtonCallback, false);
        });
        view.bind('hide', function () {
            document.removeEventListener('backbutton', disableBackButtonCallback);
        });

    };

    app.getContainingWidget = function (el, widgetType) {
        var $el = $(el);
        while (true) {
            var widget = $el.data(widgetType);
            if (widget) {
                return widget;
            }
            $el = $el.parent();
            if ($el.hasClass('.km-view')) {
                break;
            }
        }
        return null;
    };

    //
    app.showPopupMenu = function (title, items, callback) {
        var $popupMenu = $('#ui-popup-menu');
        var $menu = $popupMenu.find('.menu');
        // $menu.css('top', '100%');
        $menu.find('.title').text(title);
        var html = '';
        for (var n = 0; n < items.length; n++) {
            var item = items[n];
            html += '<li><a href="#!" data-role="link">' + item + '</a></li>';
        }
        $menu.find('ul').html(html);
        $popupMenu.fadeIn();
        var screenW = $popupMenu.width();
        var screenH = $popupMenu.height();
        var w = $menu.outerWidth();
        var h = $menu.outerHeight();
        var x = (screenW - w) / 2;
        var y = (screenH - h) / 2;
        $menu.css({
            left: x + 'px',
            bottom: 4 + 'px'
        });
        kendo.init($menu);
        $popupMenu.on('click', function (e) {
            var el = e.target;
            if (!$(el).parents('.menu').length) {
                dismiss(e);
                return;
            }
            if (el.tagName == 'A') {
                callback($(el).parent().index());
                dismiss(e);
            }
        });

        function dismiss(e) {
            if (e) {
                e.preventDefault();
            }
            $popupMenu.off('click');
            $popupMenu.fadeOut();
            $menu.css("bottom", "-100px");
            kendo.destroy($menu);
            document.removeEventListener('backbutton', dismiss);
        }

        document.addEventListener('backbutton', dismiss, false);
    };

    //
    //function _eatEvent(event) {
    //    var e = event || window.event;
    //    e.preventDefault && e.preventDefault();
    //    e.stopPropagation && e.stopPropagation();
    //    e.cancelBubble = true;
    //    e.returnValue = false;
    //    return false;
    //}
    //
    //app.preventLongPressMenu = function(node) {
    //    node.ontouchstart = _eatEvent;
    //    node.ontouchmove = _eatEvent;
    //    node.ontouchend = _eatEvent;
    //    node.ontouchcancel = _eatEvent;
    //};

    //
    app.setupButtonInput = function ($button) {
        if (inBrowser) {
            return;
        }
        var $container = $button.parent();
        var $input = $container.find('input');
        if (!$input.length) {
            $input = $('<input type="text" class="button-input"/>');
            $container.prepend($input);
        }

        var oriFocused;
        $input.on('touchstart', function (e) {
            $input[0].blur();
            oriFocused = document.activeElement;
            //if(oriFocused !== $input[0]) {
            //    alert(oriFocused.name);
            //}
            e.preventDefault();
            e.stopPropagation();
            if (!$button.hasClass('km-state-disabled')) {
                $button.addClass('km-state-active');
            }
        });

        $input.on('focus', function () {
            setTimeout(function () {
                if (oriFocused) {
                    oriFocused.focus();
                }
                else {
                    $input[0].blur();
                }
            }, 10);
        });

        $input.on('touchend', function (e) {
            $button.removeClass('km-state-active');

            var e0 = e.originalEvent;
            var x = e0.changedTouches[0].pageX;
            var y = e0.changedTouches[0].pageY;

            var offset = $input.offset();
            if (x > offset.left && y > offset.top &&
                x < offset.left + $input.outerWidth() &&
                y < offset.top + $input.outerHeight()) {
                setTimeout(function () {
                    $button.trigger('click');
                }, 10);
            }
            e.preventDefault();
            e.stopPropagation();
            //$input[0].blur();
            //$input.hide();
            //oriFocused && oriFocused.focus();
            //setTimeout(function() {
            //    if(oriFocused) {
            //        oriFocused.focus();
            //    }
            //    else {
            //        $input[0].blur();
            //    }
            //    $input.show();
            //}, 100);
            //setTimeout(function() {
            //    $(document.body).find('input[name=account]')[0].focus();
            //}, 0);

        });

    };

    //
    app.setupExternalLinks = function ($container) {
        var $links = $container.find('a');

        function makeExternalLinkHandler(url) {
            return function () {
                app.openExternal(url);
            };
        }

        for (var n = 0; n < $links.length; n++) {
            var $link = $($links[n]);
            var url = $link.attr('href') || '';
            if (url.indexOf('http') == 0) {
                $link.attr('href', '#!');
                $link.off('click').on('click', makeExternalLinkHandler(url));
            }
        }
    };


    app.scrollElToTop = function (el) {
        var scroller = app.getContainingWidget(el, 'kendoMobileScroller');
        if (scroller) {
            var $scroller = $(scroller.element);
            // 获取km-content相对浏览器的向下偏移量
            var scrollerTop = $scroller.offset().top;
            //var scrollerBottom = scrollerTop + $scroller.height();
            // 选择的项相对于浏览器的偏移量
            var elTop = $(el).offset().top;
            //var elBottom = elTop + $(el).outerHeight();
            //var dy = elBottom - scrollerBottom;

            // 获取滚动条滚动的高度
            var scrollerScrollTop = scroller.scrollTop;
            if (scrollerScrollTop === undefined) {
                scrollerScrollTop = scroller.element.scrollTop();
            }
            //scroller.lastScrollTop = scrollerScrollTop;
            //var y = -(scrollerScrollTop || 0) - dy - 12;

            // 选择的项相对于滚动页面的高度
            var dy = elTop - scrollerTop;

            var y = -scrollerScrollTop - dy + 10;
            console.log(scrollerScrollTop + "," + dy + "," + y);
            // console.log(y + " ," + dy)

            scroller.scrollTo(undefined, y);
        }
        else {
            el.scrollIntoView();
        }
    };

    //
    app.suppressBackKey = function () {
        document.addEventListener('backbutton', disableBackButtonCallback, false);
    };

    app.restoreBackKey = function () {
        setTimeout(function () {
            document.removeEventListener('backbutton', disableBackButtonCallback);
        }, 400);
    };

    app.downloadFile = function (path, fileName) {
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(path);
        var fileURL = "/mnt/sdcard/download/ykxw" + fileName;
        fileTransfer.onprogress = showUploadingProgress;
        navigator.notification.progressStart("", "当前下载进度");
        fileTransfer.download(
            uri,
            fileURL,
            function (entry) {
                console.log("download complete: " + entry.fullPath);
                navigator.notification.progressStop();
                app.showToast("下载成功，文件位置：" + entry.fullPath);
                window.event.returnValue = false;
            },
            function (error) {
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("upload error code" + error.code);
                navigator.notification.progressStop();
                app.alert("下载文件错误！");
            },
            false,
            {
                headers: {
                    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                }
            }
        );
    };

    // 显示下载进度
    function showUploadingProgress(progressEvt) {
        if (progressEvt.lengthComputable) {
            navigator.notification.progressValue(Math
                .round((progressEvt.loaded / progressEvt.total) * 100));
        }
    }

    // 设置配置
    app.setSetting = function (setting) {
        var settings = setting || {};
        localStorage.setItem('$settings', JSON.stringify(settings));
    };

    // 获取本地配置
    app.getSetting = function () {
        var stateText = localStorage.getItem('$settings') || "{}";
        return JSON.parse(stateText);
    };

    /**
     * xyb
     * 点击链接判断跳转页面
     * @param url
     */
    app.onSkipLinkBtn = function (url) {
        if (url != null && url != "") {
            if (url.indexOf("!#") == 0) {
                frame.gotoPage(url.substring(2));
            } else if (url.indexOf("/#") == 0) {
                app.gotoPage(url, "slide:left");
            }
        }
    };

    /**
     * xyb
     * 初始化 swiper轮播插件
     * @param el
     */
    app.onInitSwiper = function (el) {
        new Swiper(el, {
            loop: true,
            pagination: '.swiper-pagination',
            paginationClickable: true,
            effect: 'coverflow',
            autoplay: 2000
        });
    };

    //
    function makeEventsNamespaced(events, view) {
        var viewName = view.element.attr('id');
        var eventsArr = events.split(/\s/);
        events = '';
        for (var n = 0; n < eventsArr.length; n++) {
            var event = eventsArr[n];
            if (event.indexOf('.') === -1) {
                event += '.' + viewName;
            }
            if (n > 0) {
                events += ' ';
            }
            events += event;
        }
        return events;
    }

    app.loadDataOnEvents = function (view, events, loadDataFunc) {
        var loadDataOnShow = false;
        var showing = false;

        events = makeEventsNamespaced(events, view);

        var args;
        $(document).on(events, function () {
            args = Array.prototype.slice.call(arguments);
            args.shift();
            if (showing) {
                loadDataFunc.apply(this, args);
            }
            else {
                loadDataOnShow = true;
            }
        });
        view.bind('show', function () {
            showing = true;
            if (loadDataOnShow) {
                loadDataOnShow = false;
                loadDataFunc.apply(this, args);
            }
        });
        view.bind('hide', function () {
            showing = false;
        });
        view.bind('destroy', function () {
            $(document).off(events);
        });
    };

    app.listenOnEvents = function (view, events, callback) {
        events = makeEventsNamespaced(events, view);
        $(document).on(events, callback);
        view.bind('destroy', function () {
            $(document).off(events);
        });
    };


    // 双击退出应用
    app.onBackButton = function (e) {
        e.preventDefault();
        var nNow = Number(new Date().getTime());
        if (nNow - lastBackKeyTime < 2000) {
            navigator.app && navigator.app.exitApp();
        } else {
            lastBackKeyTime = nNow;
            app.showToast("再按一次退出简说", 2000);
        }
    };

    // 修改默认的返回实体键事件
    app.onUpdateDefaultBackButton = function (e) {
        e.preventDefault();
        kendoApp.navigate("#:back");
    };

    // 返回时底部tab的标识对应
    app.onBackTabItemActive = function (view, i) {
        view.find('.index_footer_tab .tab-item').eq(i).trigger("click");
    };
    /**
     * 验证手机号码
     */
    app.validateMobileNum = function (mobileNum) {
        var pattern = /^1[34578]\d{9}$/;
        if (pattern.test(mobileNum)) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * 验证邮箱
     * @param {Object} email
     */
    app.validateEmail = function (email) {
        var pattern = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (pattern.test(email)) {
            return true;
        } else {
            return false;
        }
    };


    window.app = app;
    window.session = {};

})();



